package com.atguigu.gmall.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


@Component
public class GlobalLoginFilter implements GlobalFilter, Ordered {
    //配置URI路径
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    //浏览器中令牌的名称
    private static final String TOKEN = "token";
    private static final String USERTEMPID = "userTempId";
    private static final String LOGINURL = "http://passport.gmall.com/login.html?originUrl=";
    //RedisConfig配置类 创建RedisTemplate 不再是原生Redis客户端
    @Resource
    private RedisTemplate redisTemplate;//格式有问题？ 有问题  K类型与V类型 格式
    @Value("${auth.url}")
    private String[] authUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.获取当前path
        String path = request.getURI().getPath();
        //2.内部资源不允许浏览器访问
        if (antPathMatcher.match("/**/inner/**", path)) {
            return getVoidMono(response, ResultCodeEnum.PERMISSION);
        }
        //3.判断当前uri是否必须登录 /auth 开始就需要登陆  否则不用登陆
        String userId = getUserId(request);
        //3.1 异步 /**/auth/** 网关 直接连接Redis校验用户是否登录  未登录 直接返回值201   登录了 放行
        if (antPathMatcher.match("/**/auth/**", path)) {
            //当前Path是需要登录的页面 判断用户是否登录
            if (StringUtils.isEmpty(userId)) {
                //未登录 异步
                return getVoidMono(response, ResultCodeEnum.LOGIN_AUTH);
            }

        }
        //3.2：同步 /trade.html /order.html  pay.html  网关路由到后面页面微服务
        for (String url : authUrl) {
            if (path.indexOf(url)!= -1 && StringUtils.isEmpty(userId)) {
                //需要登录 再判断是否登录了  未登录
                // 直接转发登录页面  同步  window.location.href 刷新页面 同步
                //重定向
                //状态码
                response.setStatusCode(HttpStatus.SEE_OTHER);
                //URL地址
                try {
                    response.getHeaders().set(HttpHeaders.LOCATION,
                            LOGINURL + URLEncoder.encode(request.getURI().toString(), "utf-8"));

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return response.setComplete();//完成后可以响应
            }

        }
        //加入购物车
        //当前是网关 传递真实用户ID给后面的微服务   请求头 K:userId V:3
        if (userId != null){
            request.mutate().header("userId", userId);
        }
        //传递临时用户id
        String userTempId = getUserTempId(request);
        if (userTempId != null){
            request.mutate().header("userTempId", userTempId);
        }

        //放行
        return chain.filter(exchange);
    }


    private Mono<Void> getVoidMono(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result<Object> r = Result.build(null, resultCodeEnum);
        String result = JSONObject.toJSONString(r);
        DataBuffer dataBuffer = response.bufferFactory().wrap(result.getBytes());
        //解决Response乱码问题
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE,
                MediaType.APPLICATION_JSON_UTF8_VALUE);
        return response.writeWith(Mono.just(dataBuffer));
    }

    //获取临时用户id
    private String getUserTempId(ServerHttpRequest request) {
        String userTempId = request.getHeaders().getFirst(USERTEMPID);
        if (StringUtils.isEmpty(userTempId)) {

            HttpCookie httpCookie = request.getCookies().getFirst(USERTEMPID);
            //同步
            if (httpCookie != null) {
                userTempId = httpCookie.getValue();
            }
        }
        return userTempId;
    }

    //判断用户是否  获取真实用户ID
    private String getUserId(ServerHttpRequest request) {
        //页面上异步Ajax请求 令牌放在请求头中  同步请求时 令牌放在Cookie中
        //1.获取令牌
        String token = request.getHeaders().getFirst(TOKEN);
        if (StringUtils.isEmpty(token)) {

            HttpCookie httpCookie = request.getCookies().getFirst(TOKEN);
            //同步
            if (httpCookie != null) {
                token = httpCookie.getValue();
            }
        }
        //2.如果请求头中有token或者从cookie中获取到了token
        if (!StringUtils.isEmpty(token)) {
            //去缓存里查询
            if (redisTemplate.hasKey(token)) {
                return (String) redisTemplate.opsForValue().get(token);
            }
        }
        //3.请求头和cookie中都没有token
        return null;
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
